package com.wan37.logic.dao.impl;

import com.wan37.logic.dao.UserItemDao;
import com.wan37.logic.domain.entity.UserItemDO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-06-17 14:49
 **/
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = Exception.class)
@Repository
public class UserItemDaoImpl implements UserItemDao {

    @Autowired
    HibernateTemplate hibernateTemplate;

    @Override
    public boolean add(UserItemDO userItemDO) {
        try {
            hibernateTemplate.save(userItemDO);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean delete(Integer id) {
        try {
            hibernateTemplate.delete(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean update(UserItemDO userItemDO) {
        try {
            Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            Query query = session.createQuery("update UserItemDO u set u.count=? where u.userId=? and u.itemId=?");
            query.setParameter(0, userItemDO.getCount());
            query.setParameter(1, userItemDO.getUserId());
            query.setParameter(2, userItemDO.getItemId());
            query.executeUpdate();
            session.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<UserItemDO> getAll() {
        return null;
    }

    @Override
    public List<UserItemDO> getUserItemDOByUserId(String userId) {
        return (List<UserItemDO>) hibernateTemplate.find("from UserItemDO where userId = ?", userId);
    }
}
